import { login, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: localStorage.getItem('name'),
    id: localStorage.getItem('id'),
    avatar: '',
    ownerId: localStorage.getItem('ownerId'),
    ownerType: localStorage.getItem('ownerType'),
    // id: localStorage.getItem('id'),
    realName: localStorage.getItem('realName'),
    roles: [],
    isLogin: false,
    hbtnName: '小通代偿'
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_OWNERID: (state, ownerId) => {
      state.ownerId = ownerId
    },
    SET_OWNERTYPE: (state, ownerType) => {
      state.ownerType = ownerType
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_REALNAME: (state, realName) => {
      state.realName = realName
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          const data = response.data
          setToken(response.token)
          commit('SET_TOKEN', response.token)
          localStorage.setItem('name', data.name)
          // localStorage.setItem('id', data.id)
          localStorage.setItem('ownerId', data.ownerId)
          localStorage.setItem('ownerType', data.ownerType)
          localStorage.setItem('id', data.id)
          localStorage.setItem('realName', data.realName)
          commit('SET_NAME', data.name)
          commit('SET_ID', data.id)
          commit('SET_OWNERID', data.ownerId)
          commit('SET_OWNERTYPE', data.ownerType)
          commit('SET_REALNAME', data.realName)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端登出
    FedLogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(response => {
          // alert("退出成功")
          // debugger
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve(response)
        }).catch(error => {
          // debugger
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          location.reload()
          console.log('退出error=' + error)
          // reject(error)
        })
      })
    }

  }
}

export default user
